package com.travelmood.controller;

import com.travelmood.pojo.Result;
import com.travelmood.pojo.User;
import com.travelmood.service.UserService;
import com.travelmood.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    //添加用户功能
    @PostMapping("/add")
    public String addUser(@RequestBody User user) {
        userService.addUser(user);
        return "用户添加成功";
    }

    //用户登录功能
    @PostMapping("/login")
    public Result login(@RequestBody User user) {
        log.info("用户登录：" + user);
        User u = userService.login(user);
        if (u != null) {
            Map<String, Object> claims = new HashMap<>();
            claims.put("userId", u.getUserId());
            claims.put("userName", u.getUserName());
            String token = JwtUtils.generateJwt(claims);
            // 创建一个 Map 或者专门的 DTO 类来返回更多的信息
            Map<String, Object> responseData = new HashMap<>();
            responseData.put("userId", u.getUserId());
            responseData.put("token", token);
            return Result.success(responseData); // 返回包含用户 ID 和令牌的 Map
        }
        return Result.error("用户名或密码错误");
    }

    //根据已登录用户 token 获取用户名，根据用户名返回用户信息
    //有token则返回成功信息，没有则返回失败信息
    @GetMapping("/info")
    public Result userInfo(@RequestHeader("Authorization") String token) {
        try {
            User userInfo = userService.getUserInfoByToken(token);
            return Result.success(userInfo);
        } catch (Exception e) {
            return Result.error("用户名或密码错误");
        }
    }


}
